package cn.touna.jss.modules.third.nifa;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.exception.ResponseException;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.NifaProperties;
import cn.touna.jss.common.util.JssConstant;
import cn.touna.jss.common.util.ShaUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.nifa.entity.NifaEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.http.HttpsUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHeaders;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 中国互金协会
 * Created by wuwuc on 2018/01/30.
 */
@Service
public class NifaService {

    private static final Logger logger = LogManager.getLogger(NifaService.class);

    @Autowired
    private NifaProperties nifaProperties;

    /**
     * 互金协会共享信息查询
     * @param requestEntity
     * @return
     */
    @ApiMapping(value="nifa.infoUpload",desc="中国互金协会.共享查询")
    public Response infoUpload(NifaEntity requestEntity) {
        logger.info("REQ 【互金协会共享信息查询】infoUpload-requestEntity：{}", requestEntity);
        Response response = new Response();
        try {
            Map<String, String> headParams = getHeadParams(requestEntity);
            Map<String, String> bodyParams = new HashMap<>();
            bodyParams.put("sname", requestEntity.getName());
            bodyParams.put("stype", requestEntity.getStype());
            bodyParams.put("sreason", requestEntity.getSreason());
            bodyParams.put("sno", requestEntity.getSno());
            String result = HttpsUtil.getInstance().post(nifaProperties.getInfoUrl(), headParams, JSON.toJSONString(bodyParams));
            //检测结果是否返回正常
            JSONObject resObj = JSONObject.parseObject(result);
            String msgCode = resObj.getString("msgCode");
            if(!"200".equals(msgCode)){
                String msgContent = resObj.getString("msgContent");
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msgContent,result);
            }
            return ResponseFactory.success(result);
        }catch (ResponseException e){
            return e.getResponse();
        }catch (Exception e) {
            logger.error("【互金协会共享信息查询】异常,infoUpload,paramMap:{}", requestEntity,e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    private Map<String, String> getHeadParams(NifaEntity requestEntity)throws ResponseException {
        Map<String, String> headParams = new HashMap<>();
        try {
            String scode = String.valueOf((long) (Math.random() * (Math.pow(10, 10))));//10位随机数
            String sbankcode = nifaProperties.getSbankcode();
            String secretKey = nifaProperties.getSecretKey();
            StringBuilder signBuilder = new StringBuilder();
            if (requestEntity != null) {
                signBuilder.append(sbankcode).append(scode).append(requestEntity.getName()).append(requestEntity.getStype())
                        .append(requestEntity.getSreason()).append(requestEntity.getSno()).append(secretKey);
            } else {
                signBuilder.append(sbankcode).append(scode).append(secretKey);
            }
            headParams.put(HttpHeaders.AUTHORIZATION, secretKey);
            headParams.put("Content-Type", JssConstant.JSON_MEDIA_TYPE);
            headParams.put("sbankcode", sbankcode);
            headParams.put("scode", scode);
            headParams.put("sign", ShaUtil.encrypt(signBuilder.toString(), "SHA-256"));
        } catch (NoSuchAlgorithmException e) {
            throw ResponseException.build(SystemErrorCodeEnum.JSS_HEAD_PARAM_ERROR,e.getMessage());
        }
        return headParams;
    }

    /*
    public Response infoUpload2(String sname,String idCard,String sreason) throws Exception {
        String url = "http://125.35.80.130:8090/NifaServer/context/info/json/upload";
        String sbankcode = "595680876";
        String scode = UUID.randomUUID().toString().replace("-","").toUpperCase().substring(0,10);
        String secretKey = "38ps4o9an89imt7j987c2pj9809oe872";
        String stype = "0";

        StringBuilder signBuilder = new StringBuilder();
        signBuilder.append(sbankcode).append(scode).append(sname).append(stype)
                .append(sreason).append(idCard).append(secretKey);
        String sign = ShaUtil.encrypt(signBuilder.toString(), "SHA-256");

        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type",HttpUtil.CONTENT_TYPE_JSON);
        headers.put("sbankcode",sbankcode);
        headers.put("scode",scode);
        headers.put("sign",sign);

        Map<String,String> body = new HashMap<>();
        body.put("sname",sname);
        body.put("stype",stype);
        body.put("sreason",sreason);
        body.put("sno",idCard);
        String res =  HttpUtil.get(url,null,headers,JSONObject.toJSONString(body));
        return ResponseFactory.success(res);
    }*/

}
